'use strict';
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var Root_Path = path.resolve(__dirname);
var Modules_Path = path.resolve(Root_Path, './node_modules');
var Entry_Path = path.resolve(Root_Path, './entry');
var ServerPort = 8081;
var Glob = require('glob');
var CleanWebpackPlugin = require('clean-webpack-plugin');

var HtmlwebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");


var Build_Path = path.resolve(Root_Path, './build');

var IsPre = false;
var IsProduction = false;
if ("pre" == process.env.PACKAGE_ENV) {
    IsPre = true;
    Build_Path = path.resolve(Root_Path, './build');
}

if ("production" == process.env.PACKAGE_ENV) {
    IsProduction = true;
    Build_Path = path.resolve(Root_Path, './build');
}

//Build_Path = path.resolve(Root_Path, './build');

var plugins = [

    new webpack.DefinePlugin({
        'process.env': {
            PACKAGE_ENV: JSON.stringify(process.env.PACKAGE_ENV),
            NODE_ENV: '"production"'
        }
    }),

    new CleanWebpackPlugin(
        [Build_Path + '/*'],　 //匹配删除的文件
        {
            root: Build_Path,       　　　　　　　　　　//根目录
            verbose: true,        　　　　　　　　　　//开启在控制台输出信息
            dry: false        　　　　　　　　　　//启用删除文件
        }
    ),

    new webpack.ProvidePlugin({
        $: "jquery",
        _: "lodash",
        API: ["@/api", "default"],
        DZ: ["@/js/utils/app.js", "default"],
        KZ: ["@/js/utils/hybrid-sdk.js", "default"],
    }),

    //new webpack.NamedModulesPlugin(),

    new webpack.optimize.CommonsChunkPlugin({
        name: 'common',
        filename: 'js/common-[chunkhash:6].js',
        minChunks: 3
    }),

    new ExtractTextPlugin({ filename: 'css/[name]-[contenthash:6].css', allChunks: true }),

    new webpack.optimize.UglifyJsPlugin({
        //sourceMap: true,
        compress: {
            warnings: false,
            drop_debugger: true, // 发布时去除debugger语句
            drop_console: IsPre || IsProduction // 发布时去除console语句
        }
    }),
]

var filenames = Glob.sync(path.resolve(Entry_Path, "**/*.js"));
//var filenames = fs.readdirSync(Entry_Path);
var entryObj = filenames.reduce(function (all, filename) {

    var name = path.basename(filename, path.extname(filename));
    all[name] = filename;

    var htmlPlugin = new HtmlwebpackPlugin({
        template: path.resolve(Root_Path, `./pages/${name}.html`),
        filename: name + ".html",
        chunks: ["common", name],
        hash: false,
        minify: {
            removeComments: true,       //去掉注释
            //collapseWhitespace: true    //去掉空格
        }
    });
    plugins.push(htmlPlugin)

    return all;
}, { "common": ["babel-polyfill", "jquery", "./css/modules/common.scss"] })


//console.log(entryObj)

module.exports = {
    module: {
        rules: [
            {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        babelrc: false,
                        presets: ['env', 'stage-0']
                        //plugins: ["transform-remove-strict-mode"]
                    }
                }
            },
            {
                test: /\.scss$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true,
                                minimize: true //css压缩
                            }
                        },
                        'postcss-loader',
                        'sass-loader'
                    ],
                    publicPath: "../"
                })
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: [
                        {
                            loader: 'css-loader',
                            options: {
                                sourceMap: true,
                                minimize: true //css压缩
                            }
                        },
                        'postcss-loader'
                    ],
                    publicPath: "../"
                })
            },
            {
                test: /\.(png|jpeg|jpg|gif)$/,
                use: {
                    loader: "url-loader",
                    options: {
                        limit: 20000,
                        name: "images/[name]-[hash:6].[ext]"
                    }
                }
            },
            {
                test: /\.(html|ejs)?$/,
                use: ['ejs-compiled-loader']
            },
        ]
    },

    entry: entryObj,

    output: {
        //filename: '[name]/[name].js',
        //chunkFilename: '[name]/[name].js',

        filename: 'js/[name]-[chunkhash:6].js',
        chunkFilename: 'js/[name]-[chunkhash:6].js',
        path: Build_Path,
        //publicPath: "./"
    },

    resolve: {
        extensions: ['.js', '.scss', '.css', '.json'],
        modules: ["node_modules"],
        alias: {
            '@': path.resolve(__dirname, '')
        }
    },

    plugins: plugins

};